﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sitecore.Data.Items;
using Sitecore.Data.Templates;
using Sitecore.Data.Managers;
using Sitecore.Data;
using Sitecore.Diagnostics;
using Sitecore.Data.DataProviders.Sql;

namespace Sitecore.ChangesTracker.Archiving
{
    public class ArchivedTemplate 
    {
        ArchivedItem template;
        List<ArchivedItem> fields;
        List<ArchivedItem> sections;
        Template currentTemplate;
        List<TemplateField> currentFields;
        List<TemplateSection> currentSections;

        private ArchivedTemplate()
        {
        }

        public static ArchivedTemplate Parse(ChangeTrackerArchiveEntry entry, List<ArchivedItem> items)
        {
            ArchivedTemplate temaplte = new ArchivedTemplate();
            temaplte.LoadCurrentState(entry.ItemId);
            temaplte.LoadArchivedState(entry, items);
            return temaplte;
        }
        void LoadCurrentState(ID templateId)
        {
            currentTemplate = TemplateManager.GetTemplate(templateId, Sitecore.Context.ContentDatabase);
            Assert.ArgumentNotNull(currentTemplate, "currentTemplate");
            currentSections = currentTemplate.GetSections().ToList();
            currentFields = currentTemplate.GetFields(false).ToList();
        }
        void LoadArchivedState(ChangeTrackerArchiveEntry entry, List<ArchivedItem> items)
        {
            template = items.First(i => i.ItemId == entry.ItemId.ToGuid());
            fields = items.Where(i => i.TemplateId == TemplateIDs.TemplateField.ToGuid()).ToList();
            sections = items.Where(i => i.TemplateId == TemplateIDs.TemplateSection.ToGuid()).ToList();
        }

        public ArchivedItem Template
        {
            get { return template; }
        }

        public List<TemplateSection> CurrentSections
        {
            get { return currentSections; }
            set { currentSections = value; }
        }

        public List<TemplateField> CurrentFields
        {
            get { return currentFields; }
            set { currentFields = value; }
        }

        public Template CurrentTemplate
        {
            get { return currentTemplate; }
            set { currentTemplate = value; }
        }

        public List<ArchivedItem> Sections
        {
            get { return sections; }
            set { sections = value; }
        }

        public List<ArchivedItem> Fields
        {
            get { return fields; }
            set { fields = value; }
        }



    }
}
